package com.changan.service.impl;

import com.alibaba.fastjson2.JSON;
import com.changan.entity.Menu;
import com.changan.mapper.MenuMapper;
import com.changan.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changan.vo.MenuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author NieChangan
 * @since 2025-09-03
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<MenuVO> findMenuTree() {
        if(redisTemplate.hasKey("menu")){
            Object o = redisTemplate.opsForHash().get("menu", "menuTree");
            return JSON.parseArray(o.toString(), MenuVO.class);
        }

        //如果对菜单进行了增删改查,那么肯定是要刷新我们的菜单列表的,直接将key移除就行了
        //redisTemplate.opsForHash().delete("menu", "menuTree");

        //查询所有的菜单
        List<Menu> list = this.list();

        //先获取所有的一级菜单
        List<MenuVO> menuVOList = new ArrayList<>();

        for (Menu menu : list) {
            if (menu.getParentId() == 0) {
                MenuVO menuVO = new MenuVO();
                //通过Spring给我们提供的工具类,复制属性
                BeanUtils.copyProperties(menu, menuVO);
                menuVOList.add(menuVO);
            }
        }

        //需要对一级菜单进行排序  jdk1.8的新特性,lambda表达式
        menuVOList.sort((o1, o2) -> o2.getOrderNum().compareTo(o1.getOrderNum()));
        //menuVOList.stream().sorted((o1, o2) -> o1.getOrderNum().compareTo(o2.getOrderNum()));
        //设置一级菜单的子菜单
        for (MenuVO menuVO : menuVOList) {
            //这里在每次循环的时候，需要给menuVO设置子菜单
            menuVO.setChildMenu(getChild(menuVO, list));
        }

        redisTemplate.opsForHash().put("menu", "menuTree", JSON.toJSONString(menuVOList));
        return menuVOList;
    }

    private List<MenuVO> getChild(MenuVO menuVO, List<Menu> list) {
        List<MenuVO> childMenuList = new ArrayList<>();
        for (Menu menu : list) {
            if (menu.getParentId().equals(menuVO.getId())) {
                MenuVO childMenu = new MenuVO();
                //通过Spring给我们提供的工具类,复制属性
                BeanUtils.copyProperties(menu, childMenu);
                childMenuList.add(childMenu);
            }
        }

        for (MenuVO childMenu : childMenuList) {
            childMenu.setChildMenu(getChild(childMenu, list));
        }

        //要对菜单的orderNum值进行升序排序
        childMenuList.sort((o1, o2) -> o1.getOrderNum().compareTo(o2.getOrderNum()));

        //如果节点下没有子节点，返回一个空List（递归退出）
        if(childMenuList.isEmpty()){
            return new ArrayList<MenuVO>();
        }
        return childMenuList;
    }
}
